import math
import os
from datetime import datetime, timedelta
import matplotlib.dates as mdates

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 设置字体以支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

# 颜色映射
# colors = {
#     0: '#000000',# 黑色
#     1: '#FF0000',# 红色
#     2: '#FF1493',# 粉红
#     3: '#FF34B3',# 桃红
#     4: '#FF3E96',# 粉紫
#     11: '#CD00CD',# 紫罗兰
#     12: '#D15FEE',# 粉紫
#     13: '#7D26CD',# 紫
#     14: '#4F4F4F',# 灰色
#     15: '#0000FF',# 蓝色
#     16: '#00FFFF',# 青色
#     21: '#228B22',# 绿色
#     22: '#B8860B',# 橙色
#     23: '#A0522D',# Sienna
#     24: '#FFA500',# 橙色
#     25: '#00C5CD',# 青色
#     26: '#66CDAA'# Aquamarine
# }
colors = {
    0: (0, 100, 0),       # 深绿色
    1: (0, 0, 255),       # 蓝色
    2: (139, 0, 0),       # 深红色
    3: (75, 0, 130),      # 深紫色
    4: (139, 69, 19),     # 深棕色
    11: (205, 133, 63),    # 深橙色
    12: (0, 105, 105),     # 深青色
    13: (139, 0, 139),     # 深洋红色
    14: (40, 40, 40),      # 深灰色
    15: (85, 107, 47),     # 深橄榄绿
    16: (0, 105, 148),     # 深海蓝
    21: (255, 0, 139),     # 深酒红
    22: (85, 65, 0),       # 深咖啡色
    23: (22, 55, 22),     # 深苔藓绿
    24: (0, 0, 128),       # 深蓝色
    25: (0, 206, 209),    # 青色
    26: (102, 205, 170)   # Aquamarine
}


class ShowTimeDuration:
    def __init__(self):
        self.path = ''
        self.data = {}
        self.car_data = {}
        self.p85 = None

    def read_file(self, path):
        self.path = path
        self.get_data()
        self.show(flag=False)
        self.show(flag=True)
        self.clear()

    def read_file1(self, path, data_list):
        self.path = path
        self.get_data()
        self.show1(data_list, flag=False)
        self.show1(data_list, flag=True)
        self.clear()

    def show1(self, data_list, flag=False):
        if flag:
            k = 1
            v = self.data[k]
            duration_seconds = []
            times_keys = list(v.keys())
            times = [datetime.strptime(time, '%H:%M') for time in times_keys]
            for key, value in v.items():
                duration_seconds.append(value['duration_seconds'])
            data = {
                'x': times,
                'y': duration_seconds
            }

            plt.scatter(data['x'], data['y'], color=[c / 255 for c in colors[k]], label='车型：' + str(k))  # 绘制散点图
        else:
            for k, v in self.data.items():
                duration_seconds = []
                times_keys = list(v.keys())
                times = [datetime.strptime(time, '%H:%M') for time in times_keys]
                for key, value in v.items():
                    duration_seconds.append(value['duration_seconds'])
                data = {
                    'x': times,
                    'y': duration_seconds
                }

                plt.scatter(data['x'], data['y'], color=[c / 255 for c in colors[k]], label='车型：' + str(k))  # 绘制散点图

        for i in range(len(data_list)):
            x1_line = data_list[i]['start'].split(' ')[1][:5]
            x2_line = data_list[i]['end'].split(' ')[1][:5]
            x_1 = datetime.strptime(x1_line, '%H:%M')
            x_2 = datetime.strptime(x2_line, '%H:%M')
            # 绘制垂直线
            plt.axvline(x=x_1, color='green', linestyle='--')
            plt.axvline(x=x_2, color='black', linestyle='--')
            # 添加标注
            plt.text(x_1, 1.03, str(data_list[i]['level']), ha='center', va='bottom', transform=plt.gca().get_xaxis_transform())

        # 设置X轴为每1小时一个标记
        ax = plt.gca()  # 获取当前的Axes
        fig = ax.figure
        fig.set_size_inches(20, 12)  # 宽度为10英寸，高度为6英寸
        # ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # 每1小时一个主要刻度
        ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 30], interval=1))  # 每半小时一个主要刻度
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
        plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式

        # 添加标签和标题
        ax.set_xlabel('时间')
        ax.set_ylabel('通行时间（秒）')
        if flag:
            ax.set_title('小客车通行散点图')
        else:
            ax.set_title('所有车型通行散点图')
        ax.legend(loc='upper right')

        # # 显示图表
        # plt.show()

        # 保存图表到文件
        output_dir = os.path.join(os.path.dirname(self.path), 'png1')
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        file_name = os.path.basename(self.path).split('.')[0]
        if flag:
            output_filename = os.path.join(output_dir, file_name + '_car.png')
        else:
            output_filename = os.path.join(output_dir, file_name + '_all.png')
        plt.savefig(output_filename, dpi=200)
        # 关闭图表以释放内存
        plt.close()

    def show(self, flag=False):

        if flag:
            k = 1
            v = self.data[k]
            duration_seconds = []
            times_keys = list(v.keys())
            times = [datetime.strptime(time, '%H:%M') for time in times_keys]
            for key, value in v.items():
                duration_seconds.append(value['duration_seconds'])
            data = {
                'x': times,
                'y': duration_seconds
            }

            plt.scatter(data['x'], data['y'], color=[c / 255 for c in colors[k]], label='车型：' + str(k))  # 绘制散点图
        else:
            for k, v in self.data.items():
                duration_seconds = []
                times_keys = list(v.keys())
                times = [datetime.strptime(time, '%H:%M') for time in times_keys]
                for key, value in v.items():
                    duration_seconds.append(value['duration_seconds'])
                data = {
                    'x': times,
                    'y': duration_seconds
                }

                plt.scatter(data['x'], data['y'], color=[c / 255 for c in colors[k]], label='车型：' + str(k))  # 绘制散点图

        # 设置X轴为每1小时一个标记
        ax = plt.gca()  # 获取当前的Axes
        fig = ax.figure
        fig.set_size_inches(20, 12)  # 宽度为10英寸，高度为6英寸
        # ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # 每1小时一个主要刻度
        ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 30], interval=1))  # 每半小时一个主要刻度
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
        plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式

        # 添加标签和标题
        ax.set_xlabel('时间')
        ax.set_ylabel('通行时间（秒）')
        if flag:
            ax.set_title('小客车通行散点图')
        else:
            ax.set_title('所有车型通行散点图')
        ax.legend(loc='upper right')

        # # 显示图表
        # plt.show()

        # 保存图表到文件
        output_dir = os.path.join(os.path.dirname(self.path), 'png')
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        file_name = os.path.basename(self.path).split('.')[0]
        if flag:
            output_filename = os.path.join(output_dir, file_name + '_car.png')
        else:
            output_filename = os.path.join(output_dir, file_name + '_all.png')
        plt.savefig(output_filename, dpi=200)
        # 关闭图表以释放内存
        plt.close()

    def get_data(self):
        df_up = pd.read_csv(self.path)
        data0 = df_up.to_dict(orient='records')
        self.data = {}
        for i in range(len(data0)):
            time = data0[i]['transtime_down'].split(' ')[1][:5]
            ctype = data0[i]['feevehicletype']
            if ctype not in self.data:
                self.data[ctype] = {}

            self.data[ctype][time] = {
                "vlp": data0[i]['vlp'],
                "duration_seconds": data0[i]['duration_seconds']
            }

    def clear(self):
        self.data = {}
        self.car_data = {}
        self.p85 = None
        self.path = ''


if __name__ == '__main__':

    # A区中度1
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240131\car_time_data.csv'
    # A区重度1
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240207\car_time_data.csv'
    # A区重度2
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240219\car_time_data.csv'
    # A区重度3
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240205\car_time_data.csv'
    # A区轻度1
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240117\car_time_data.csv'
    # 重度
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240330\car_time_data.csv'
    # B区
    # path = r'D:\GJ\项目\事故检测\output\G004251001000210010,G004251001000310010-20240421\car_time_data.csv'
    # path = r'D:\GJ\项目\事故检测\output\G004251001000320010,G004251001000220010-20240502\car_time_data.csv'
    # 其他
    # path = r'D:\GJ\项目\事故检测\output\G004251001000210010,G004251001000310010-20240101\car_time_data.csv'

    # C区
    # path = r'D:\GJ\项目\事故检测\output\G004251001000120020,G004251001000120010-20240416\car_time_data.csv'

    name = "G004251002000620010,G004251001000320010-20240404"
    path0 = r'D:\GJ\项目\事故检测\output\邻垫高速'
    path = os.path.join(path0, name, 'time_duration_data.csv')

    showTimeDuration = ShowTimeDuration()
    showTimeDuration.read_file(path)
